package com.example.controllers;

import com.example.utils.RestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
public class HelloController {

    private static final Logger log  = LoggerFactory.getLogger(HelloController.class);

    @RequestMapping("/hello")
    public String hello() {
        return "Hello Spring Boot!";
    }

    @RequestMapping("/needLogin")
    public RestResponse needLogin(HttpServletRequest request) {
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        String currentUser = request.getHeader("currentUser");

        return RestResponse.success("登录用户的token为："+token+",登录用户为："+currentUser);
    }

    @RequestMapping("/noneedlogin")
    public RestResponse noneedlogin(HttpServletRequest request) {
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        String currentUser = request.getHeader("currentUser");

        return RestResponse.success("不需要登录。token为："+token+",登录用户为："+currentUser);
    }

    @RequestMapping("/timeout")
    public String timeout(Integer timeout) {
        log.info("请求到达，将休眠："+timeout+"毫秒");
        try {
            Thread.sleep(timeout);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "延时"+timeout+"执行，执行结束!";
    }

    @RequestMapping("/uploadimg4")
    public String uploadimg4() {
        return "这是被转换后的接口";
    }

    @RequestMapping("/dologin")
    public RestResponse dologin(String userName) {

        if(!StringUtils.hasLength(userName)){
            return RestResponse.build(1,"请输入用户名，userName=xxxx");
        }else {
            if("admin".equals(userName)){
                return RestResponse.success("登录成功");
            }else{
                return RestResponse.build(201,"用户名错误,请使用userName=admin进行登录");
            }
        }

    }

    @RequestMapping("/uploadImg2")
    public RestResponse importDriverInfo( @RequestParam("divisionId")Integer divisionId,
                                          @RequestParam("file") MultipartFile file) {
        log.info("测试信息，参数为：partnerId="+ divisionId+"divisionId="+ divisionId);
        String deposeFilesDir = "D:\\wp\\spring-gate-way-test\\";
        // 判断文件手否有内容
        if (file.isEmpty()) {
            log.info("该文件无任何内容!!!");
        }else{
            // 获取附件原名(有的浏览器如chrome获取到的是最基本的含 后缀的文件名,如myImage.png)
            // 获取附件原名(有的浏览器如ie获取到的是含整个路径的含后缀的文件名，如C:\\Users\\images\\myImage.png)
            String fileName = file.getOriginalFilename();
            // 如果是获取的含有路径的文件名，那么截取掉多余的，只剩下文件名和后缀名
            int index = fileName.lastIndexOf("\\");
            if (index > 0) {
                fileName = fileName.substring(index + 1);
            }
            // 判断单个文件大于1M
            long fileSize = file.getSize();
            if (fileSize > 1024 * 1024) {
                log.info("文件大小为(单位字节):" + fileSize);
                log.info("该文件大于1M");
            }
            // 当文件有后缀名时
            if (fileName.indexOf(".") >= 0) {
                // split()中放正则表达式; 转义字符"\\."代表 "."
                String[] fileNameSplitArray = fileName.split("\\.");
                // 加上random戳,防止附件重名覆盖原文件
                fileName = fileNameSplitArray[0] + (int) (Math.random() * 100000) + "." + fileNameSplitArray[1];
            }
            // 当文件无后缀名时(如C盘下的hosts文件就没有后缀名)
            if (fileName.indexOf(".") < 0) {
                // 加上random戳,防止附件重名覆盖原文件
                fileName = fileName + (int) (Math.random() * 100000);
            }
            log.info("fileName:" + fileName);

            // 根据文件的全路径名字(含路径、后缀),new一个File对象dest
            File dest = new File(deposeFilesDir + fileName);
            // 如果该文件的上级文件夹不存在，则创建该文件的上级文件夹及其祖辈级文件夹;
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                // 将获取到的附件file,transferTo写入到指定的位置(即:创建dest时，指定的路径)
                file.transferTo(dest);
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            log.info("文件的全路径名字(含路径、后缀)>>>>>>>" + deposeFilesDir + fileName);
        }


        return RestResponse.success("ok");
    }
}
